package com.gzz.orchid.common.core.validation.validator;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.*;

/**
 * &#064;CheckFlag(value  = {"0", "1"}, message = "标志位有误")
 *
 * @author higmd
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Constraint(validatedBy = CheckFlag.Validator.class) // 绑定对应校验器
public @interface CheckFlag {
    String[] value() default {};

    String message() default "flag is not found";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 标志位校验器
     */
    class Validator implements ConstraintValidator<CheckFlag, Integer> {
        private String[] values;

        /**
         * 初始化
         *
         * @param validator 注解上设置的值
         */
        @Override
        public void initialize(CheckFlag validator) {
            this.values = validator.value();
        }

        /**
         * 校验
         *
         * @param value                      被校验的值，即输入
         * @param constraintValidatorContext 校验上下文
         * @return 返回true证明校验通过，false校验失败
         */
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
            boolean isValid = false;
            // 当value为null，校验失败
            if (value == null) {
                return false;
            }
            //遍历校验
            for (String s : values) {
                if (s.equals(String.valueOf(value))) {
                    isValid = true;
                    break;
                }
            }
            return isValid;
        }
    }
}
